package com.yami.shop.webservice.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.mail.MailException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.bean.enums.PaySeviceTypeCode;
import com.yami.shop.bean.model.TransferTokenRecord;
import com.yami.shop.bean.vo.DawToVo;
import com.yami.shop.common.bean.HSExchange;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.DataWebService;
import com.yami.shop.common.util.DateUtils;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.webservice.common.service.TransferTokenRecordService;
import com.yami.shop.webservice.common.service.WapiDawService;
import com.yami.shop.webservice.common.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WapiDawServiceImpl implements WapiDawService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ShopConfig shopConfig;
    @Autowired
    private TransferTokenRecordService transferTokenRecordService;
    @Autowired
    private DataWebService dataWebService;
    @Override
    public Map<String, Object> changeCeceipt(List<DawToVo> dawList,String applyId) throws MailException {
        //获取请求内容
        if(dawList.size()==0){
            throw new MailException("划转数产不能为空");
        }
        //{applyId:12331,"dataList":[{regWeight:"100",idNumber:"0000005584","varietyCode":"CP2","dataMap":{tokenid:123,aaaa:aaaa}}]   }
//        Minio minio = shopConfig.getMinio();
        JSONArray dataArray = new JSONArray();
        for (DawToVo dawToVo:dawList) {
            //校验
            TransferTokenRecord record= transferTokenRecordService.selectByTokenId(dawToVo.getTokenId(),0);
            if(ObjectUtil.isNotNull(record)&&record.getStatus()==0){
                throw new MailException("重复划转："+dawToVo.getTokenId());
            }
            //扩展参数
            JSONObject dataMap = new JSONObject();
            dataMap.put("denomId",dawToVo.getDenomId());
            dataMap.put("denomName",dawToVo.getDenomName());
            dataMap.put("mainImg",dawToVo.getMainImg());
            dataMap.put("tokenId",dawToVo.getTokenId());
            dataMap.put("dawName",dawToVo.getDawName());
            dataMap.put("author",dawToVo.getAuthor());
            dataMap.put("issue",dawToVo.getIssue());
            dataMap.put("fileType",dawToVo.getFileType());
            dataMap.put("dawCode",dawToVo.getDawCode());
            dataMap.put("levelId",dawToVo.getLevelId());
            //基本参数
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("userId",dawToVo.getUserId());
            jSONObject.put("varietyCode",dawToVo.getVarietyCode());
            jSONObject.put("isClick",dawToVo.getIsClick());
            jSONObject.put("regWeight",dawToVo.getRegWeight());
            jSONObject.put("dataMap",dataMap);
            dataArray.add(jSONObject);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("applyId",applyId);
        map.put("dataList",dataArray);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口获取服务商code参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostObjWebService(apiGatewayUrl + PaySeviceTypeCode.function_id14,map);
        JSONObject jsonObject = null;
        try {
            jsonObject =  JSON.parseObject(result);
        }catch (Exception e){
            log.error("apigataway超时"+result);
            throw new MailException("超时"+result);
        }
        // 组装外层通用参数 发起审核通知
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                return (Map<String,Object>)ress;
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public String getchangeCeceipt(List<DawToVo> dawList, String applyHwjId) throws MailException {
        //获取请求内容
        JSONArray dataArray = new JSONArray();
        for (DawToVo dawToVo:dawList) {
            //校验
            TransferTokenRecord record= transferTokenRecordService.selectByTokenId(dawToVo.getTokenId(),0);
            if(ObjectUtil.isNotNull(record)&&record.getStatus()==0){
                throw new MailException("重复划转："+dawToVo.getTokenId());
            }
            //扩展参数
            JSONObject dataMap = new JSONObject();
            dataMap.put("denomId",dawToVo.getDenomId());
            dataMap.put("denomName",dawToVo.getDenomName());
            dataMap.put("mainImg",dawToVo.getMainImg());
            dataMap.put("tokenId",dawToVo.getTokenId());
            dataMap.put("dawName",dawToVo.getDawName());
            dataMap.put("author",dawToVo.getAuthor());
            dataMap.put("issue",dawToVo.getIssue());
            dataMap.put("fileType",dawToVo.getFileType());
            dataMap.put("dawCode",dawToVo.getDawCode());
            dataMap.put("levelId",dawToVo.getLevelId());
            //基本参数
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("userId",dawToVo.getUserId());
            jSONObject.put("varietyCode",dawToVo.getVarietyCode());
            jSONObject.put("isClick",dawToVo.getIsClick());
            jSONObject.put("regWeight","1");
            jSONObject.put("dataMap",dataMap);
            dataArray.add(jSONObject);
        }
        JSONObject jSONObject = new JSONObject();
        jSONObject.put("applyId",applyHwjId);
        jSONObject.put("dataList",dataArray);
        HSExchange hsExchange = shopConfig.getAPIExchange();
        //基础参数
        Map<String, Object> orgParam = new HashMap<>();
        orgParam.put("version", "v1");
        orgParam.put("app_id",hsExchange.getAppId());
        orgParam.put("charset","UTF-8");
        orgParam.put("timestamp", DateUtils.dateToString(new Date()));
        orgParam.put("biz_content",jSONObject.toJSONString());
        //获取sign
        orgParam.put("sign", MD5Utils.md5Two("UTF-8",jSONObject.toJSONString(),hsExchange.getAppSecret()));
        StringBuilder targetUrl = new StringBuilder();
        for (Map.Entry<String, Object> entry : orgParam.entrySet()) {
            targetUrl.append(entry.getKey()).append("=").append( entry.getValue()).append("&");
        }
        String param = targetUrl.substring(0, (targetUrl.length() - 1)).toString();
        // 组装外层通用参数 发起审核通知
        log.info("获验恒生转仓地址"+hsExchange.getAppUrl()+"/wapi/card/"+ PaySeviceTypeCode.function_id14);
        return param;
    }

    @Override
    public JSONArray getChangeCeceiptResult(List<String>  applyIdList) throws YamiShopBindException {
        //获取请求内容
        if(applyIdList.size()==0){
            throw new YamiShopBindException("查询的请求不能为空");
        }
        JSONArray dataArray = new JSONArray();
        for (String applyId:applyIdList) {
            JSONObject obj = new JSONObject();
            obj.put("applyId",applyId);
            dataArray.add(obj);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("applyIdList",dataArray);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("获验恒生转仓结果查询参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostObjWebService(apiGatewayUrl + PaySeviceTypeCode.function_id19,map);
        log.info("获验恒生转仓结果查询返回"+result);
        JSONObject jsonObject = null;
        try {
            jsonObject =  JSON.parseObject(result);
        }catch (Exception e){
            log.error("apigataway超时"+result);
            throw new YamiShopBindException("超时"+result);
        }
        // 组装外层通用参数 发起审核通知
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                return jsonObject.getJSONArray("data");
            }else{
                log.error(jsonObject.getString("msg"));
                throw new YamiShopBindException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new YamiShopBindException("第三方发起接口返回空");
        }
    }
}
